package com.dart.commons.base.web.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.dart.commons.constants.AppConst;

/**
 * Web层辅助类
 * 
 * @author yhaoquan
 * 
 */
public final class WebUtil {
	private WebUtil() {
	}

	/** 保存当前用户 */
	public static final void saveCurrentUser(Object user) {
		setSession(AppConst.CURRENT_USER, user);
	}

	/** 获取当前用户ID */
	public static final Integer getCurrentUserId() {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			if (null != session) {
				return (Integer) session.getAttribute(AppConst.CURRENT_USER);
			}
		}
		return null;
	}

	/**
	 * 将一些数据放到ShiroSession中,以便于其它地方使用
	 * 
	 * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
	 */
	public static final void setSession(Object key, Object value) {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			if (null != session) {
				session.setAttribute(key, value);
			}
		}
	}

	/** 移除当前用户 */
	public static final void removeCurrentUser(HttpServletRequest request) {
		request.getSession().removeAttribute(AppConst.CURRENT_USER);
	}

}
